﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SDT.Model;
using SDT.Lib.Common;
using System.Linq.Dynamic;
using SDT.Lib.Paging;
using SDT.Admin.ViewModels;
using SDT.Lib.Helpers;
namespace SDT.Admin.Controllers
{
	[RoleHelper(Roles = RoleSystem.Dictionary)]
    public class MenuController : Controller
    {
        //
        // GET: /Menu/
        ChoVietDataContext eDataContext = new ChoVietDataContext();
        public ActionResult Index()
        {
            try
            {
                    string order = UserState.getUserStateFromRequest("menu.order", "order", "ID").ToString();
                    string orderDir = UserState.getUserStateFromRequest("menu.orderDir", "orderDir", "desc").ToString();

                    string keyword = UserState.getUserStateFromRequest("menu.Keyword", "Keyword", "").ToString();
                    var typeid = Utils.ParseInt(UserState.getUserStateFromRequest("menu.Type", "ddlMenuType", 0));

                    var pageNumber = Convert.ToInt32(UserState.getUserStateFromRequest("menu.PageNumber", "page", 1));
                    var pageIndex = pageNumber - 1;
                    var pageSize = Convert.ToInt32(UserState.getUserStateFromRequest("menu.PageSize", "pageSize", 20));

                    var menus = eDataContext.Menus
                        .Where(a => typeid > 0 ? a.TypeID == typeid : true)                        
                        .Where(a => string.IsNullOrEmpty(keyword) ? true :
                            a.Name.ToLower().Contains(keyword.ToLower().Trim()))
                        .OrderBy(string.Format("{0} {1}", order, orderDir))
                        .ToPagedList(pageIndex, pageSize);

                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;
                    MenuViewIndexModel m = new MenuViewIndexModel();
                    m.Menus = menus;
                    m.MenuTypes = eDataContext.MenuTypes.ToList();
                    m.FilterName = keyword;
					m.CurrentMenuType = typeid;
                    return View(m);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Menu/Details/5
        public ActionResult Details(int id)
        {
            try
            {
                    var item = eDataContext.Menus.SingleOrDefault(e => e.ID == id);
                    return View(item);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Menu/Create
        public ActionResult Create()
        {
            try
            {
                    return View(
                        new MenuViewEditModel
                        {
                            MenuTypes = eDataContext.MenuTypes.ToList(),
                            Menus = eDataContext.Menus.Where(e=>e.ParentID==null).ToList() 
                        });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        } 

        //
        // POST: /Menu/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(MenuViewEditModel m)
        {
            try
            {
                    UpdateModel(m);
                    var pid = Utils.ParseInt(Request["ddlParentMenu"]);
                    var leve1 = Utils.ParseInt(Request["ddlParentMenuLeve1"]);
                    pid = leve1 > 0 ? leve1 : pid;

                    var typeid = Utils.ParseInt(Request["ddlMenuType"]);
                    var chkPub = Request["chkPublic"] != null && Request["chkPublic"] != "false" ? true : false;
                    var pm = pid > 0 ? eDataContext.Menus.Where(e => e.ID == pid).SingleOrDefault() : null;
                    m.Menu.ParentID = pm != null ? pm.ID : (int?)null;
                    m.Menu.TypeID = pm != null ? pm.TypeID : typeid;
                    m.Menu.PubYN = chkPub;
                    m.Menu.ModifyBy = UserManager.GetUserId();
                    m.Menu.ModifyDate = DateTime.Now;
                    m.Menu.AddBy = UserManager.GetUserId();
                    m.Menu.AddDate = DateTime.Now;

                    eDataContext.Menus.InsertOnSubmit(m.Menu);
                    eDataContext.SubmitChanges();
                    
                    var linkleftid = Utils.ParseInt(Request["ddlParentMenuLeft"]);
                    if (linkleftid > 0 && m.Menu.TypeID==MenuListType.Top) {
                        MenuMap map = new MenuMap();
                        map.MenuTopID = m.Menu.ID;
                        map.LinkToID = linkleftid;
                        eDataContext.MenuMaps.InsertOnSubmit(map);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        
        //
        // GET: /Menu/Edit/5
        public ActionResult Edit(int id)
        {
            try
            {
                    var m=eDataContext.Menus.Where(e=>e.ID==id).SingleOrDefault();
                    return View(
                        new MenuViewEditModel
                        {
                            MenuTypes = eDataContext.MenuTypes.ToList(),
                            Menus = eDataContext.Menus.Where(e => e.ParentID == null).ToList(),
                            Menu=m,
                            LinkMenus = m.MenuMaps.Count > 0 ? eDataContext.Menus.Where(e => (e.TypeID == m.MenuMaps[0].LinkMenu.TypeID) && (e.ParentID == null)).ToList() : 
                                eDataContext.Menus.Where(e => (e.TypeID == MenuListType.Left) && (e.ParentID == null)).ToList()
                        });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Menu/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, MenuViewEditModel m)
        {
            try
            {
                    m.Menu = eDataContext.Menus.Where(e => e.ID == id).SingleOrDefault();
                    UpdateModel(m);
                    var pid = Utils.ParseInt(Request["ddlParentMenu"]);
                    var typeid = Utils.ParseInt(Request["ddlMenuType"]);
                    var langid = Utils.ParseInt(Request["ddlLanguage"]);
                    var chkPub = Request["chkPublic"] != null && Request["chkPublic"] != "false" ? true : false;

                    var pm = pid > 0 ? eDataContext.Menus.Where(e => e.ID == pid).SingleOrDefault() : null;
                    m.Menu.ParentID = pm != null ? pm.ID : (int?)null;
                    m.Menu.TypeID = pm != null ? pm.TypeID : typeid;

                    m.Menu.PubYN = chkPub;
                    m.Menu.ModifyBy = UserManager.GetUserId();
                    m.Menu.ModifyDate = DateTime.Now;
                    m.Menu.AddBy = UserManager.GetUserId();
                    m.Menu.AddDate = DateTime.Now;
                    eDataContext.SubmitChanges();

                    eDataContext.MenuMaps.DeleteAllOnSubmit(from d in eDataContext.MenuMaps where d.MenuTopID == id select d);
                    eDataContext.SubmitChanges();
                    var linkleftid = Utils.ParseInt(Request["ddlParentMenuLeft"]);
                    if (linkleftid > 0 && m.Menu.TypeID == MenuListType.Top)
                    {
                        MenuMap map = new MenuMap();
                        map.MenuTopID = m.Menu.ID;
                        map.LinkToID = linkleftid;
                        eDataContext.MenuMaps.InsertOnSubmit(map);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Menu/Delete/5
        public ActionResult Delete(int id)
        {
            try
            {
                    var item = eDataContext.Menus.SingleOrDefault(e => e.ID == id);
                    return View(item);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Menu/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                    var item = eDataContext.Menus.SingleOrDefault(e => e.ID == id);
                    if (item != null)
                    {
                        eDataContext.MenuMaps.DeleteAllOnSubmit(from m in eDataContext.MenuMaps where m.MenuTopID == id || m.LinkToID == id select m);
                        eDataContext.Menus.DeleteAllOnSubmit(from m in eDataContext.Menus where m.ParentID==id select m);
                        eDataContext.Menus.DeleteOnSubmit(item);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
    }
}
